package com.cjd.common

import android.annotation.TargetApi
import android.content.pm.PackageManager
import android.os.Build
import android.os.StrictMode
import androidx.multidex.MultiDexApplication
import com.cjd.common.preferences.JsonPreference
import com.cjd.common.preferences.UserPreference
import com.cjd.common.utils.ActivityLifecycleCallbacksUtil
import com.cjd.common.utils.DisplayUtil
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.Logger


/**
 * @Author chenjidong
 * @email 374122600@qq.com
 * created 2019/9/20
 * description
 */
open class BaseApplication : MultiDexApplication() {

    companion object {
        @JvmField
        var VERSION_CODE = 0
        @JvmField
        var VERSION_NAME = ""
    }

    override fun onCreate() {
        super.onCreate()
        DisplayUtil.init(this)
        JsonPreference.init(this)
        UserPreference.init(this)
        getVersionInfo()
        Logger.addLogAdapter(object : AndroidLogAdapter() {
            override fun isLoggable(priority: Int, tag: String?): Boolean {
                return BuildConfig.DEBUG
            }
        })

        compatibilityCamera()
        ActivityLifecycleCallbacksUtil.register(this)
    }

    override fun onTerminate() {
        super.onTerminate()
        ActivityLifecycleCallbacksUtil.unregister(this)
    }

    /**
     * android 7.0系统解决拍照的问题
     * @blob https://blog.csdn.net/qq_23179075/article/details/70314473
     * @bug android.os.FileUriExposedException: file:///storage/emulated/0/photo.jpeg exposed beyond app through ClipData.Item.getUri()
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private fun compatibilityCamera() {
        val builder = StrictMode.VmPolicy.Builder()
        StrictMode.setVmPolicy(builder.build())
        builder.detectFileUriExposure()
    }

    private fun getVersionInfo() {

        val pm = packageManager
        try {
            val packageInfo = pm.getPackageInfo(packageName, 0)
            VERSION_CODE = packageInfo.versionCode
            VERSION_NAME = packageInfo.versionName
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }

    }
}